import React, { useContext, useEffect, useRef, useState } from 'react'
import { DatePicker, Form, Input, InputNumber } from 'antd'
import Select from '../Select'
import TreeSelect from '../TreeSelect'

const EditableContext = React.createContext(null)

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm()
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  )
}

const EditableCell = ({
  editable,
  dataIndex,
  record,
  //类型 N=数值，S=下拉框，T=下拉树，默认输入框
  dataType,
  //数值属性
  min,
  max,
  precision,
  //选择框属性
  options,
  allowClear,
  handleSave,
  uppercase,
  rules,
  treeData,
  maxLength,
  inputOptions,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false)
  const inputRef = useRef(null)
  const form = useContext(EditableContext)

  useEffect(() => {
    if (editing) {
      inputRef.current.focus()
    }
  }, [editing])

  const toggleEdit = () => {
    setEditing(!editing)
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    })
  }

  const save = async () => {
    try {
      const values = await form.validateFields()
      toggleEdit()
      handleSave({ ...record, ...values })
    } catch (errInfo) {
      console.log('Save failed:', errInfo)
    }
  }

  const EditComponent = () => {
    switch (dataType) {
      case 'N': {
        return (
          <InputNumber
            autoComplete={'off'}
            precision={precision || 0}
            min={min || 0}
            max={max || 100000000000000000000}
            style={{ width: '100%' }}
            ref={inputRef}
            onPressEnter={save}
            onBlur={save}
          />
        )
      }
      case 'S': {
        return (
          <Select
            style={{ width: '100%' }}
            ref={inputRef}
            virtual={false}
            allowClear={allowClear}
            options={options}
            onChange={save}
            onBlur={save}
          />
        )
      }
      case 'T': {
        return (
          <TreeSelect
            style={{ width: '100%' }}
            ref={inputRef}
            dropdownStyle={{ minHeight: 270, maxHeight: 350 }}
            virtual={false}
            treeIcon
            treeData={treeData}
            onChange={save}
            onBlur={save}
          />
        )
      }
      case 'D': {
        return (
          <DatePicker
            style={{ width: '100%' }}
            ref={inputRef}
            onChange={save}
          />
        )
      }
      default:
        return (
          <Input
            autoComplete={'off'}
            spellCheck={false}
            style={uppercase ? { width: '100%', textTransform: 'uppercase' } : { width: '100%' }}
            maxLength={maxLength || 999999}
            ref={inputRef}
            onPressEnter={save}
            onBlur={save}
          />
        )
    }
  }

  return (
    <td {...restProps}>
      {editable ? (
        (
          editing ? (
            <Form.Item
              name={dataIndex}
              style={{ margin: 0 }}
              initialValue={record[dataIndex]}
              rules={rules ? rules : []}
            >
              {EditComponent()}
            </Form.Item>
          ) : (
            <div
              className="editable-cell-value-wrap"
              onClick={toggleEdit}
            >
              {restProps.children}
            </div>
          )
        )
      ) : restProps.children}
    </td>
  )
}

EditableCell.defaultProps = {
  inputOptions: {},
}

export { EditableCell, EditableRow }